package project.Dao;

import project.Entity.Message;
import project.Entity.User;
import project.util.DbConn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MessageDao {
    private Connection conn = DbConn.getConn();

    /////查询
    public List<Message> queryRecord(String email, String toEmail){
        System.out.println("查询聊天记录");
        String sql = "select * from msg_record where ((host=? and toWho=?) or (host=? and toWho=?)) ORDER BY time DESC;";
        List<Message> list = new ArrayList<>();
        PreparedStatement pstmt;
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, email);
            pstmt.setString(2, toEmail);
            pstmt.setString(3, toEmail);
            pstmt.setString(4, email);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String id = rs.getString("id");
                String host = rs.getString("host");
                String toWho = rs.getString("toWho");
                String content = rs.getString("content");
                String time = rs.getString("time");
                Message msg = new Message(Integer.parseInt(id),host,toWho,content,time);
                list.add(msg);
            }
            pstmt.close();
            System.out.println("操作成功！已关闭数据库连接。");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    ////插入
    public boolean saveMessage(Message message){
        System.out.println("正在保存信息");
        String sql = "insert into msg_record (host, toWho, content, time) values(?,?,?,(select now()))";
        int a = 0;
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, message.host);
            pstmt.setString(2, message.toWho);
            pstmt.setString(3, message.content);
            a = pstmt.executeUpdate();
            pstmt.close();
            System.out.println("操作成功！已关闭数据库连接。");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a > 0;
    }
    ////插入
    public boolean deleteMessage(String email1, String email2){
        System.out.println("正在保存信息");
        String sql = "delete from msg_record where (host=? and toWho=?) or (host=? and toWho=?)";
        int a = 0;
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, email1);
            pstmt.setString(2, email2);
            pstmt.setString(3, email2);
            pstmt.setString(4, email1);
            a = pstmt.executeUpdate();
            pstmt.close();
            System.out.println("操作成功！已关闭数据库连接。");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a > 0;
    }
}
